package com.learn.im.controller;

import com.google.common.collect.Maps;
import com.learn.im.domain.R;
import com.learn.im.utils.AuthUtils;
import com.learn.im.websocket.IMServer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;


/**
 * @author Emp
 * @version :    1.0
 */
@Controller
@RequestMapping("im/user")
public class UserController {

    @Resource
    private IMServer imServer;

    @ResponseBody
    @PostMapping("onlineusers")
    public R onlineUsers(){
        Collection<String> users = imServer.onlineUser();
        return R.ok("在线用户获取成功",users);
    }

    @PostMapping("loginvalidate")
    public void loginValidate(String username, String password, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Collection<String> onlineUser = imServer.onlineUser();
        if (onlineUser.contains(username)){
            response.getWriter().write("duplicate username");
        }else {
            request.getSession().setAttribute("username", username);
            response.sendRedirect("/view/chatroom.html");
        }
    }

    @ResponseBody
    @GetMapping("currentuser")
    public R currentUser(HttpServletRequest request){
        return R.ok("查询成功",AuthUtils.currentUsername(request.getSession()));
    }

}
